# -*- coding: utf-8 -*-

from typing import Dict
import json


def dlist2ddict(dlist: list, parse_col_name: str) -> Dict[int, dict]:
    """数据库查询返回的字典列表，转化为以指定列(一般为主键)的值为键的字典"""
    ddict = {}
    for d in dlist:
        ddict[d[parse_col_name]] = d
    return ddict


def deal_with_source_data(case_dlist: list, step_dlist: list, element_dlist: list):
    case_ddict = dlist2ddict(dlist=case_dlist, parse_col_name='case_id')
    for step in step_dlist:  # 把测试步骤加到测试用例下
        step['data'] = json.loads(step['data'])
        step['expected'] = json.loads(step['expected'])
        step['output'] = json.loads(step['output'])

        if step['snippet_id']:  # 用例片段类型处理
            snippet = str(step['snippet_id'])
            snippet_setting = step['snippet_setting']
            if snippet_setting:  # 用例片段执行配置
                snippet_setting: dict = json.loads(snippet_setting)
                executeCount = snippet_setting.get('executeCount', '1')
                exitCondition = snippet_setting.get('exitCondition', 'false')
                errorStillRun = snippet_setting.get('errorStillRun', 'false')
                snippet += f'*{executeCount}'
                if errorStillRun == 'true':
                    snippet += '*'
                if exitCondition == 'true':
                    step['data']['循环结束条件'] = '成功'
                elif exitCondition == 'false':
                    step['data']['循环结束条件'] = '失败'
            step['element'] = snippet
        case_id = step['case_id']
        if not case_ddict[case_id].get('steps'):
            case_ddict[case_id]['steps'] = [step]
        else:
            case_ddict[case_id]['steps'].append(step)
    case = []
    for src_case in case_ddict.values():  # 测试步骤排序
        step = src_case.get('steps')
        if step:
            src_case['steps'] = sorted(step, key=lambda x: x['seq_num'])
        case.append(src_case)
    # for element in element_dlist:  # 元素frame处理
    #     if element['frame_id']:
    #         element['custom'] = frame_ddict[str(element['frame_id'])]
    return {'case': case}



